from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from cart.utils import merge_cookie_cart_to_redis
from oauth.exceptions import QQAPIError
from oauth.models import OAuthQQUser
from oauth.serializers import OauthQQUserViewSerializer
from oauth.utils import OAuthQQ
import logging

logger = logging.getLogger()


class QQAuthURLView(APIView):
    """获取qq登录的网址"""

    def get(self, request):
        next = request.query_params.get('next', '/')
        # 获取qq登录地址
        # 创建对象
        oauth = OAuthQQ(state=next)
        # 调用方法使用
        login_url = oauth.get_login_url()

        return Response({'login_url': login_url})


# class QQAuthUserView(APIView):
#     """获取qq的openid"""
#
#     def get(self, request):
#         # 获取qq的code
#         code = request.query_params.get("code")
#
#         try:
#             oauth = OAuthQQ()
#             access_token = oauth.get_access_token(code)
#             # 根据access_token获取openid
#             openid = oauth.get_openid(access_token)
#         except QQAPIError as e:
#             logger.error(e)
#             return Response({"message": "QQ服务器异常"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
#
#         # 根据openid查询数据库，查看qq用户是否已经绑定过
#         try:
#             oauth_user = OAuthQQUser.objects.get(openid=openid)
#         except OAuthQQUser.DoesNotExist:
#             # 如果未绑定，加密并把openid加密返回
#             token = oauth.generate_save_user_token(openid)
#             return Response({'access_token': token})
#         else:
#             # 4.1 如果已经绑定，生成JWT token信息
#             # 补充生成记录登录状态的token
#             user = oauth_user.user
#
#             # 导入
#             from rest_framework_jwt.settings import api_settings
#             # 生成token:
#             jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
#             jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
#             # 生成载荷信息(payload)
#             payload = jwt_payload_handler(user)
#             # 生成 jwt token
#             token = jwt_encode_handler(payload)
#
#             response = Response({
#                 'token': token,
#                 'user_id': user.id,
#                 'username': user.username
#             })
#             return response

class QQAuthUserView(GenericAPIView):
    # 指定序列化器
    serializer_class = OauthQQUserViewSerializer

    # POST /oauth/qq/user
    def post(self, request):
        # 保存用户登录登录数据
        # 1、获取参数并进行校验 参数的完整性 手机号g格式 验证码 密码 access_token
        # 2、进行保存数据
        # 3、返回给前端数据
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 保存
        user = serializer.save()

        # 调用merge_cookie_cart_to_redis函数实现购物车记录的合并
        response = Response(serializer.data, status=status.HTTP_201_CREATED)
        merge_cookie_cart_to_redis(request, user, response)

        return response

    def get(self, request):

        # 1. 获取QQ返回的code
        code = request.query_params.get('code')
        try:
            # 2. 根据code获取access_token
            # 2.1 创建oauth对象
            oauth = OAuthQQ()
            # 2.2 获取access_token
            access_token = oauth.get_access_token(code)
            # 3. 根据access_token获取授权QQ用户的openid
            openid = oauth.get_openid(access_token)
        except QQAPIError as e:
            logger.error(e)
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 4. 根据`openid`查询tb_oatu_qq表，判断是否已经绑定账号
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 4.2 如果未绑定，返回token
            access_token = OAuthQQ.generate_save_user_token(openid)
            return Response({'access_token': access_token})

        else:
            # 4.1 如果已经绑定，生成JWT token信息
            # 补充生成记录登录状态的token
            user = oauth_user.user

            # 导入
            from rest_framework_jwt.settings import api_settings
            # 生成token:
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 生成载荷信息(payload)
            payload = jwt_payload_handler(user)
            # 生成 jwt token
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            # 调用merge_cookie_cart_to_redis函数实现购物车记录的合并
            merge_cookie_cart_to_redis(request, user, response)

            return response
